<template>
  <view class="search-container">
    <!-- 搜索头部 -->
    <view class="search-header">
      <view class="search-box">
        <uni-icons type="search" size="20" color="#999"></uni-icons>
        <input 
          class="search-input" 
          type="text" 
          v-model="searchKeyword"
          placeholder="请输入书名关键词"
          @confirm="handleSearch"
          confirm-type="search"
        />
        <text class="clear-btn" v-if="searchKeyword" @click="clearSearch">×</text>
      </view>
      
      <!-- 类型筛选 -->
      <view class="filter-section">
        <text class="filter-label">类型筛选：</text>
        <scroll-view class="type-scroll" scroll-x>
          <view class="type-tags">
            <text 
              class="type-tag" 
              :class="{ active: selectedType === '' }"
              @click="selectType('')"
            >
              全部
            </text>
            <text 
              class="type-tag" 
              :class="{ active: selectedType === type }"
              v-for="type in bookTypes" 
              :key="type"
              @click="selectType(type)"
            >
              {{ type }}
            </text>
          </view>
        </scroll-view>
      </view>
      
      <!-- 搜索按钮 -->
      <button class="search-btn" @click="handleSearch" :disabled="loading">
        {{ loading ? '搜索中...' : '搜索' }}
      </button>
    </view>

    <!-- 搜索结果 -->
    <scroll-view class="search-results" scroll-y>
      <!-- 搜索统计 -->
      <view class="search-stats" v-if="searchResults.length > 0 || hasSearched">
        <text>找到 {{ searchResults.length }} 本相关书籍</text>
      </view>

      <!-- 书籍列表 -->
      <view class="book-list">
        <view 
          class="book-item" 
          v-for="(book, index) in searchResults" 
          :key="book.bookId"
          @click="goToDetail(book.bookId)"
        >
          <image 
            class="book-cover" 
            :src="book.cover || '/static/屏幕截图 2025-06-22 200009.png'" 
            mode="aspectFill" 
          />
          <view class="book-info">
            <text class="book-name">{{ book.bookName }}</text>
            <text class="book-author">作者：{{ book.author }}</text>
            <view class="book-meta">
              <text class="book-score" v-if="book.score">★ {{ book.score }}</text>
              <text class="book-type">{{ book.bookType }}</text>
            </view>
            <text class="book-publisher" v-if="book.publisher">{{ book.publisher }}</text>
            <text class="book-isbn" v-if="book.isbn">ISBN: {{ book.isbn }}</text>
            <text class="book-intro" v-if="book.introduction">{{ book.introduction }}</text>
          </view>
          <uni-icons type="forward" size="16" color="#ccc"></uni-icons>
        </view>
      </view>

      <!-- 空状态 -->
      <view class="empty-state" v-if="!loading && hasSearched && searchResults.length === 0">
        <image src="/static/images/no-search.png" mode="aspectFit" />
        <text class="empty-title">未找到相关书籍</text>
        <text class="empty-desc">试试其他关键词或类型筛选</text>
      </view>

      <!-- 默认状态 -->
      <view class="default-state" v-if="!loading && !hasSearched">
        <image src="/static/images/search-default.png" mode="aspectFit" />
        <text class="default-title">发现好书</text>
        <text class="default-desc">输入书名或选择类型开始搜索</text>
        
        <!-- 热门推荐 -->
        <view class="hot-keywords">
          <text class="hot-title">热门搜索：</text>
          <text 
            class="hot-keyword" 
            v-for="keyword in hotKeywords" 
            :key="keyword"
            @click="searchHotKeyword(keyword)"
          >
            {{ keyword }}
          </text>
        </view>
      </view>

      <!-- 加载状态 -->
      <view class="loading-state" v-if="loading">
        <text>搜索中...</text>
      </view>
    </scroll-view>
  </view>
</template>

<script setup>
import { ref, onMounted } from 'vue'

const searchKeyword = ref('')
const selectedType = ref('')
const searchResults = ref([])
const loading = ref(false)
const hasSearched = ref(false)
const BASE_URL = 'http://192.168.153.1:8080'

// 书籍类型列表
const bookTypes = ref([
  '科幻', '现代文学', '魔幻现实', '推理', '现实主义', 
  '古典文学', '历史', '哲学', '心理学', '经济学'
])

// 热门搜索关键词
const hotKeywords = ref([
  '三体', '活着', '百年孤独', '白夜行', '盖茨比'
])

// 页面加载时的初始化
onMounted(() => {
  console.log('搜索页面已加载')
})

// 选择类型
const selectType = (type) => {
  selectedType.value = type
  if (hasSearched.value) {
    handleSearch()
  }
}

// 清空搜索
const clearSearch = () => {
  searchKeyword.value = ''
}

// 热门关键词搜索
const searchHotKeyword = (keyword) => {
  searchKeyword.value = keyword
  handleSearch()
}

// 执行搜索
const handleSearch = async () => {
  try {
    if (!searchKeyword.value.trim() && !selectedType.value) {
      uni.showToast({
        title: '请输入搜索关键词或选择类型',
        icon: 'none'
      })
      return
    }

    loading.value = true
    hasSearched.value = true

    // 构建JSON请求数据
    const requestData = {}
    
    if (searchKeyword.value.trim()) {
      requestData.keyword = searchKeyword.value.trim()
    }
    
    if (selectedType.value) {
      requestData.bookType = selectedType.value
    }

    console.log('搜索请求参数:', requestData)

    // 使用Promise包装uni.request
    const response = await new Promise((resolve, reject) => {
      uni.request({
        url: `${BASE_URL}/books/getBooksByBookNameOrType`,
        method: 'POST',
        data: requestData,
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          console.log('请求成功:', res)
          resolve(res)
        },
        fail: (err) => {
          console.error('请求失败:', err)
          reject(err)
        }
      })
    })

    console.log('搜索API响应:', response)

    if (response.statusCode === 200) {
      if (response.data && response.data.code === 200200) {
        const booksData = response.data.data?.books || []
        
        // 映射数据字段
        searchResults.value = booksData.map(book => ({
          bookId: book.book_id,
          bookName: book.book_name,
          author: book.author,
          score: book.score,
          bookType: book.book_type,
          publisher: book.publisher,
          isbn: book.isbn,
          introduction: book.introduction,
          cover: book.cover_url || ''
        }))

        console.log('处理后的搜索结果:', searchResults.value)
        
        if (searchResults.value.length > 0) {
          uni.showToast({
            title: `找到${searchResults.value.length}本书籍`,
            icon: 'success'
          })
        } else {
          uni.showToast({
            title: '未找到相关书籍',
            icon: 'none'
          })
        }
      } else {
        throw new Error(response.data?.message || '搜索失败')
      }
    } else {
      throw new Error(`HTTP ${response.statusCode}: ${response.data?.message || '请求失败'}`)
    }
  } catch (error) {
    console.error('搜索失败:', error)
    searchResults.value = []
    uni.showToast({
      title: '搜索失败: ' + (error.message || '网络错误'),
      icon: 'none'
    })
  } finally {
    loading.value = false
  }
}

// 跳转到书籍详情
const goToDetail = (bookId) => {
  try {
    if (!bookId) {
      uni.showToast({
        title: '书籍ID无效',
        icon: 'none'
      })
      return
    }
    
    // 记录浏览历史
    recordViewHistory(bookId)
    
    uni.navigateTo({
      url: `/pages/bookdetail/bookdetail?id=${bookId}`
    })
  } catch (error) {
    console.error('跳转详情页失败:', error)
    uni.showToast({
      title: '跳转失败',
      icon: 'none'
    })
  }
}

// 记录浏览历史
const recordViewHistory = async (bookId) => {
  try {
    const user = uni.getStorageSync('userInfo')
    if (!user?.U_Id) return

    await new Promise((resolve, reject) => {
      uni.request({
        url: `${BASE_URL}/history/add`,
        method: 'POST',
        data: {
          userId: user.U_Id,
          bookId: bookId
        },
        header: {
          'Content-Type': 'application/json'
        },
        success: (res) => {
          console.log('记录浏览历史成功:', res)
          resolve(res)
        },
        fail: (err) => {
          console.error('记录浏览历史失败:', err)
          reject(err)
        }
      })
    })
  } catch (error) {
    console.error('记录浏览历史失败:', error)
  }
}
</script>

<style lang="scss">
.search-container {
  height: 100vh;
  background-color: #f5f5f5;
  display: flex;
  flex-direction: column;
}

.search-header {
  background-color: #fff;
  padding: 20rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.search-box {
  display: flex;
  align-items: center;
  background-color: #f8f8f8;
  border-radius: 25rpx;
  padding: 0 20rpx;
  margin-bottom: 20rpx;

  .search-input {
    flex: 1;
    height: 70rpx;
    font-size: 28rpx;
    margin-left: 15rpx;
  }

  .clear-btn {
    font-size: 40rpx;
    color: #999;
    padding: 10rpx;
  }
}

.filter-section {
  margin-bottom: 20rpx;

  .filter-label {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 15rpx;
    display: block;
  }

  .type-scroll {
    white-space: nowrap;
  }

  .type-tags {
    display: flex;
    gap: 15rpx;

    .type-tag {
      font-size: 24rpx;
      color: #666;
      background-color: #f0f0f0;
      padding: 12rpx 24rpx;
      border-radius: 30rpx;
      white-space: nowrap;
      transition: all 0.3s;

      &.active {
        background-color: #3a7afe;
        color: #fff;
      }
    }
  }
}

.search-btn {
  width: 100%;
  height: 80rpx;
  background-color: #3a7afe;
  color: #fff;
  border: none;
  border-radius: 40rpx;
  font-size: 30rpx;
  font-weight: bold;

  &:disabled {
    background-color: #ccc;
  }
}

.search-results {
  flex: 1;
  padding: 20rpx;
}

.search-stats {
  padding: 20rpx 0;
  text-align: center;
  font-size: 26rpx;
  color: #666;
}

.book-list {
  background-color: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.book-item {
  display: flex;
  align-items: flex-start;
  padding: 25rpx;
  border-bottom: 1rpx solid #f0f0f0;
  transition: background-color 0.2s;

  &:last-child {
    border-bottom: none;
  }

  &:active {
    background-color: #f8f8f8;
  }

  .book-cover {
    width: 120rpx;
    height: 160rpx;
    border-radius: 8rpx;
    margin-right: 20rpx;
    background-color: #f0f0f0;
    flex-shrink: 0;
  }

  .book-info {
    flex: 1;
    display: flex;
    flex-direction: column;
    gap: 8rpx;

    .book-name {
      font-size: 32rpx;
      font-weight: bold;
      color: #333;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
    }

    .book-author {
      font-size: 26rpx;
      color: #666;
    }

    .book-meta {
      display: flex;
      align-items: center;
      gap: 20rpx;

      .book-score {
        font-size: 24rpx;
        color: #ff6b35;
        font-weight: 500;
      }

      .book-type {
        font-size: 22rpx;
        color: #3a7afe;
        background-color: #ecf5ff;
        padding: 4rpx 12rpx;
        border-radius: 20rpx;
        border: 1rpx solid #d4edff;
      }
    }

    .book-publisher {
      font-size: 24rpx;
      color: #888;
    }

    .book-isbn {
      font-size: 22rpx;
      color: #aaa;
      font-family: monospace;
    }

    .book-intro {
      font-size: 24rpx;
      color: #999;
      display: -webkit-box;
      -webkit-box-orient: vertical;
      -webkit-line-clamp: 2;
      overflow: hidden;
      line-height: 1.4;
    }
  }

  uni-icons {
    margin-left: 20rpx;
    margin-top: 20rpx;
  }
}

.empty-state, .default-state {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 100rpx 40rpx;
  text-align: center;

  image {
    width: 200rpx;
    height: 200rpx;
    margin-bottom: 40rpx;
    opacity: 0.6;
  }

  .empty-title, .default-title {
    font-size: 32rpx;
    color: #333;
    font-weight: bold;
    margin-bottom: 15rpx;
  }

  .empty-desc, .default-desc {
    font-size: 26rpx;
    color: #999;
    margin-bottom: 40rpx;
  }
}

.hot-keywords {
  width: 100%;

  .hot-title {
    font-size: 26rpx;
    color: #666;
    margin-bottom: 20rpx;
    display: block;
  }

  .hot-keyword {
    display: inline-block;
    font-size: 24rpx;
    color: #3a7afe;
    background-color: #ecf5ff;
    padding: 8rpx 16rpx;
    border-radius: 20rpx;
    margin: 0 10rpx 10rpx 0;
    border: 1rpx solid #d4edff;
  }
}

.loading-state {
  display: flex;
  justify-content: center;
  align-items: center;
  padding: 100rpx 0;
  font-size: 28rpx;
  color: #999;

  &::before {
    content: '';
    width: 30rpx;
    height: 30rpx;
    border: 3rpx solid #e0e0e0;
    border-top-color: #3a7afe;
    border-radius: 50%;
    animation: spin 1s linear infinite;
    margin-right: 20rpx;
  }
}

@keyframes spin {
  0% { transform: rotate(0deg); }
  100% { transform: rotate(360deg); }
}

/* 响应式设计 */
@media screen and (max-width: 750rpx) {
  .book-item {
    .book-cover {
      width: 100rpx;
      height: 130rpx;
    }
    
    .book-info {
      .book-name {
        font-size: 30rpx;
      }
    }
  }
}
</style>